#!/usr/bin/env python 2.7
# -*- coding: utf-8 -*-
# @Time      :2020/11/27
# @Author    :Erinyu
# @Email     :yuailing@bbdservice.com
# @File      :IC_Past24MonsGuaranAmt
# @Software  :PyCharm

'''eof
name:个人近24个月对外担保金额
code:IC_Past24MonsGuaranAmt
tableName:
columnName:
groups:个人征信模块
dependencies:IC_DSJ
type:常用指标
datasourceType:在线指标
description:
eof'''

import json
import sys
import re
import datetime

reload(sys)
sys.setdefaultencoding('utf-8')

null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']

def getTable(data, tableName, occurTimes, iteratorTimes):
    '''
        获取表信息
        :param data:表上层的字典对象
        :param tableName:表的名字
        :param occurTimes:表出现的次数，如果是0代表此表可以不出现，如果是1代表此表必须出现
        :param iteratorTimes:下级字段出现的次数，如果是0代表下级字段可以不出现，如果是1代表下级字段必须出现
        :return:该表全部数据  返回[{}]为异常缺失，返回0为正常缺失，其他返回正常数组
        '''
    try:
        table = data.get(tableName)
        if occurTimes == 0:
            if table is None or (table == "" and iteratorTimes == 0):
                return 0
            elif isinstance(table, list) is False or len(table) == 0 or (table == "" and iteratorTimes == 1):
                return [{}]
            else:
                return table
        if occurTimes == 1:
            if table == "" and iteratorTimes == 0:
                return 0
            if table is None or isinstance(table, list) is False or len(table) == 0 \
                    or (table == "" and iteratorTimes == 1):
                return [{}]
            else:
                return table
    except:
        return [{}]

def NaNCheck(str):
    return False if str in null_type_list else True

def intCheck(str):
    try:
        int(str)
        return True
    except:
        return False

def Formate(time):
    r = re.compile(r'\D+')
    try:
        date = datetime.datetime.strptime(time, '%Y.%m.%d').strftime('%Y-%m-%d')
    except:
        try:
            date = datetime.datetime.strptime(time, '%Y-%m-%d').strftime('%Y-%m-%d')
        except:
            try:
                date = datetime.datetime.strptime(time, '%Y/%m/%d').strftime('%Y-%m-%d')
            except:
                try:
                    tmp = r.sub('', time)
                    if len(tmp) == 6:
                        date = datetime.datetime.strptime(tmp, '%Y%m').strftime('%Y-%m-%d')
                    else:
                        date = datetime.datetime.strptime(tmp, '%Y%m%d').strftime('%Y-%m-%d')
                except:
                    date = None
    return date

def past24Mons(time):
    time = time.replace('-', '')
    past24ago = '{}{}'.format(int(datetime.datetime.now().strftime('%Y%m%d')[:4]) - 2,
                                 datetime.datetime.now().strftime('%m%d'))
    return time >= past24ago


# 个人近24个月对外担保金额
# Factor1= [相关还款责任金额 PD03AJ01 [1.1] ]
# where (相关还款责任信息PCR - 相关还款责任信息单元（PD03） - 相关还款责任信息段（PD03A）)
# 开立日期在（PD03AR01）在 24个月内
# Formate(PD03AR01) is not None and past24Mons(Formate(PD03AR01))
# and 相关还款责任人类型（PD03AD03）== '2'
# Factor=sum(factor1)
# PCR[1.1] - PD03[0.*] - PD03A[1.1] - PD03AR01[1.1]/PD03AD03[1.1]/PD03AJ01[1.1]

def IC_Past24MonsGuaranAmt():
    data = IC_DSJ.get('data')
    factor = []
    # 相关还款责任信息 PCR [1.1]
    PCR = getTable(data, 'PCR', 1, 0)
    if PCR == [{}]:
        return u'缺失值'
    elif PCR == 0:
        return 0
    else:
        # 相关还款责任信息单元 PD03 [0.*]
        PD03 = getTable(PCR[0], 'PD03', 0, 1)
        if PD03 == [{}]:
            return u'缺失值'
        elif PD03 == 0:
            return 0
        else:
            for i in PD03:
                # 相关还款责任信息段 PD03A [1.1]
                PD03A = getTable(i, 'PD03A', 1, 1)
                if PD03A == [{}]:
                    return u'缺失值'
                # 因为PD03A的occurTimes、iteratorTimes都是1
                # 根据getTable函数定义，不可能值为0,所以这里就不判断为0的情况了
                else:
                    # 相关还款责任人类型 PD03AD03 [1.1] == '2'
                    PD03AD03 = PD03A[0].get('PD03AD03')
                    # 开立日期 PD03AR01 [1.1] 在 24 个月内
                    PD03AR01 = PD03A[0].get('PD03AR01')
                    if not (NaNCheck(PD03AD03) and intCheck(PD03AD03)) and Formate(PD03AR01) is None:
                        # 缺失值
                        factor.append(None)
                    else:
                        if PD03AD03 == '2' and past24Mons(Formate(PD03AR01)):
                            # 相关还款责任金额 PD03AJ01 [1.1]
                            PD03AJ01 = PD03A[0].get('PD03AJ01')
                            if not (NaNCheck(PD03AJ01) and intCheck(PD03AJ01)):
                                # 缺失值
                                factor.append(None)
                            else:
                                factor.append(int(PD03AJ01))
                        else:
                            # 不是缺失值，只是不符合条件
                            factor.append(0)

    factor = [x for x in factor if x is not None]
    return u'缺失值' if len(factor) == 0 else sum(factor)

if __name__ == '__main__':
    file_obj = open(r'IC_DSJ.json', 'r')
    content = file_obj.read()
    IC_DSJ = json.loads(content, strict=False)
    IC_DSJ = IC_DSJ.get('IC_DSJ')
    res = IC_Past24MonsGuaranAmt()
    print(res)

result = IC_Past24MonsGuaranAmt()